package api

import (
	"api-getway/basic/config"
	__ "api-getway/basic/proto"
	"api-getway/handler/req"
	"github.com/gin-gonic/gin"
	"net/http"
)

type ResPonce struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

// SendSms 短信发送
func SendSms(c *gin.Context) {
	var so req.SendSmsRequest
	err := c.ShouldBind(&so)
	if err != nil {
		c.JSON(http.StatusBadRequest, &ResPonce{
			Code: 400,
			Msg:  "参数错误",
			Data: err.Error(),
		})
		return
	}

	r, err := config.UserClient.SendSms(c, &__.SendSmsReq{Phone: so.Phone})
	if err != nil {
		c.JSON(http.StatusBadRequest, &ResPonce{
			Code: 400,
			Msg:  "短信发送失败",
			Data: err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, &ResPonce{
		Code: 200,
		Msg:  "短信发送成功",
		Data: r,
	})
}

// Register 用户注册
func Register(c *gin.Context) {
	var so req.RegisterRequest
	err := c.ShouldBind(&so)
	if err != nil {
		c.JSON(http.StatusBadRequest, &ResPonce{
			Code: 400,
			Msg:  "参数错误",
			Data: err.Error(),
		})
		return
	}

	r, err := config.UserClient.Register(c, &__.RegisterReq{
		Phone:    so.Phone,
		Password: so.Password,
		NewCode:  so.NewCode,
	})

	if err != nil {
		c.JSON(http.StatusBadRequest, &ResPonce{
			Code: 400,
			Msg:  "用户注册失败",
			Data: err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, &ResPonce{
		Code: 200,
		Msg:  "用户注册成功",
		Data: r,
	})
}

// Login 用户登录
func Login(c *gin.Context) {
	var so req.LoginRequest
	err := c.ShouldBind(&so)
	if err != nil {
		c.JSON(http.StatusBadRequest, &ResPonce{
			Code: 400,
			Msg:  "参数错误",
			Data: err.Error(),
		})
		return
	}

	r, err := config.UserClient.Login(c, &__.LoginReq{
		Phone:   so.Phone,
		NewCode: so.NewCode,
	})

	if err != nil {
		c.JSON(http.StatusBadRequest, &ResPonce{
			Code: 400,
			Msg:  "用户登录失败",
			Data: err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, &ResPonce{
		Code: 200,
		Msg:  "用户登录成功",
		Data: r,
	})
}
